<?php

namespace library;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Env;

class JwtToken
{
    /**
     * @desc 生成token
     * @param $data
     * @return string
     */
    public function createJwt($data = [])
    {
        $key = Env::get('JWT_KEY');
        $time = time(); //签发时间
        $expire = $time + 3600 * 24 * 30; //过期时间
        $data = array(
            "data" => $data,
            "iss" => Env::get('JWT_ISS'),//签发组织
            "aud" => "zzw", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwtStr = JWT::encode($data, md5($key), 'HS256');
        return $jwtStr;
    }

    /**
     * @desc 验证token
     * @param $jwt
     * @return mixed
     */
    public function verifyJwt($jwt = 'default.default.default')
    {
        $key = Env::get('JWT_KEY');
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, new Key(md5($key), 'HS256')));
            $authInfo = json_decode($jwtAuth, true);
        } catch (\Exception $e) {
            throw new OWException('JWT-Token解析错误', $e->getMessage());
        }

        return $authInfo['data'];
    }
}